<?php

/**
 * Description of SiteController
 * 
 * @author trongkhoi
 * @since Jun 28, 2013 - 10:00:41 AM
 */
class SiteController extends MyController
{

    public function actions()
    {
        return array(
            'captcha' => array(
                'class'     => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'foreColor' => 0x0099CC,
            ),
        );
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    private function topSevenService($biz_id)
    {
        $popular_sv = Service::model()->findAll(array(
            'condition' => "author_id=$biz_id",
            'with'      => 'appointCount',
            'select'    => "(SELECT COUNT(*) FROM tbl_appoint WHERE service_id = t.sid) AS appointCount,s_name,avatar",
            'order'     => 'appointCount desc',
            'limit'     => 7
        ));
        return $popular_sv;
    }

    public function actionError()
    {
        $this->layout = 'login';
        $error        = Yii::app()->errorHandler->error;
        if ($error)
        {
            $this->render('error', $error);
        }
    }

    public function actionSignup()
    {
        if (!Yii::app()->user->isGuest)
        {
            $this->redirect(array('site/index'));
        }

        $this->layout = 'login';
        $model        = new UserSignUp('signup');

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'signup-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['UserSignUp']))
        {
            $model->attributes = $_POST['UserSignUp'];
            $model->type       = Users::TYPE_CUSTOMER;
            $model->status     = Users::STATUS_ACTIVE;
            if ($model->validate())
            {
                $model->date_created = time();

                if ($model->save())
                {
                    //update role and update ukey
                    $model->completeCreateUser();

                    // send email to new user
                    MyEmail::sendToNewUser($model, $_POST['UserSignUp']['new_pass']);

                    Yii::app()->user->setFlash('success', 'Signup successfully, please login !');
                    $this->redirect(array('site/login'));
                }
                else
                {
                    Yii::app()->user->setFlash('error', 'Please fill correct information !');
                }
            }
        }

        $this->render('signup', array('model' => $model));
    }

    /**
     * Merchant/Staff login page
     */
    public function actionLogin()
    {
        $this->_login(array(Users::TYPE_ADMIN, Users::TYPE_STAFF));
    }

    //array $roles
    private function _login($roles, $redirect = "")
    {
        if (!Yii::app()->user->isGuest)
        {
            if (!empty($redirect))
                $this->redirect($redirect);
            else
                $this->redirect(array('site/index'));
        }
        $this->layout = 'login';

        $model = new UserLoginForm;
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        // collect user input data
//        if (isset($_POST['role']) && in_array($_POST['role'], $roles))
//        {
            if (isset($_POST['UserLoginForm']))
            {
                $model->username      = trim($_POST['UserLoginForm']['username']);
                $model->password   = trim($_POST['UserLoginForm']['password']);
                $model->rememberMe = isset($_POST['UserLoginForm']['rememberMe']) ? true : false;
                // validate user input and redirect to the previous page if valid
                if ($model->login())
                {
                    $log       = new AccessLog();
                    $log->ip   = ip2long(Yii::app()->request->userHostAddress);
                    $user      = Users::model()->findByPk(Yii::app()->user->id);
                    $log->name = $user->username;
                    $log->role = $user->type;
                    $log->time = time();
                    $log->save();
                    if (!empty($redirect))
                        $this->redirect($redirect);
                    else
                        $this->redirect(array('site/index'));
                }
            }
//        }
        $this->render('login', array('model' => $model, 'redirect' => $redirect));
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(array('site/login'));
    }

    public function actionForgotPassword()
    {
        $this->layout = 'login';
        if (!Yii::app()->user->isGuest)
        {
            $this->redirect(array('site/index'));
        }

        $model = new Users('forgotpwd');
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'forgotpassword-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['Users']) && isset($_POST['role']) && $_POST['role'] != Users::TYPE_ADMIN)
        {
            $model->email = $_POST['Users']['email'];
            $role         = $_POST['role'];
            $user         = Users::model()->find('LOWER(email)=:email AND type=:type', array(
                ':email' => strtolower($model->email),
                ':type'  => $role
            ));
            if ($user == NULL)
            {
                Yii::app()->user->setFlash('error', 'Email not found or wrong account type!');
            }
            else
            {
                $this->_sendConfirmForgotPasswordEmail($user->email, $user->ukey, $user->name);
                Yii::app()->user->setFlash('success', 'An email has been sent to you to change your password. It will expire in 2 hours.');
                $this->redirect('login');
            }
        }
        $this->render('forgotpass', array('model' => $model));
    }

    private function _sendConfirmForgotPasswordEmail($email, $ukey, $name)
    {
        $confirm = EmailConfirm::model()->find('email=:e AND type=:t', array(
            ':e' => $email,
            ':t' => EmailConfirm::TYPE_PASSWORD_RESET
        ));

        if ($confirm == NULL)
        {
            $confirm        = new EmailConfirm();
            $confirm->email = $email;
            $confirm->type  = EmailConfirm::TYPE_PASSWORD_RESET;
        }

        $code            = md5(time() . EmailConfirm::TYPE_PASSWORD_RESET);
        $confirm->code   = $code;
        //2hour
        $confirm->expire = time() + 2 * 3600;
        $confirm->save();
        $confirm_url     = Yii::app()->createAbsoluteUrl('site/resetPassword', array(
            'code' => $code,
            'ukey' => $ukey
        ));
        $mail            = new MyEmail();
        $mail->type      = MyEmail::TYPE_MERCHANT_PASSWORD_RECOVER_CONFIRM;
        $mail->to        = $email;
        $mail->params    = array(
            MyEmail::CODE_EMAIL                       => $email,
            MyEmail::CODE_USER_NAME                   => $name,
            MyEmail::CODE_PASSWORD_RESET_CONFIRM_LINK => $confirm_url,
        );
        $mail->send();
    }

    public function actionResetPassword()
    {
        if (!Yii::app()->user->isGuest)
        {
            $this->redirect(array('site/index'));
        }

        $this->layout = 'login';
        if (empty($_GET))
        {
            throw new CHttpException(400, Yii::t('yii', 'Something wrong or time expired!'));
        }

        $criteria         = new CDbCriteria();
        $criteria->select = array('ukey', 'id', 'email', 'firstname', 'lastname', 'password', 'salt', 'business_name', 'type');
        $criteria->compare('ukey', $_GET['ukey']);

        $user    = Users::model()->find($criteria);
        //check link expired or not?
        $confirm = EmailConfirm::model()->find('email=:e AND code=:c AND expire > :t AND type=:type', array(
            ':e'    => $user->email,
            ':c'    => $_GET['code'],
            ':t'    => time(),
            ':type' => EmailConfirm::TYPE_PASSWORD_RESET
        ));

        if ($user == NULL or $confirm == NULL)
        {
            throw new CHttpException(400, Yii::t('yii', 'Something wrong or time expired!'));
        }
        else
        {
            $user->new_pass = Utils::genRandomString();
            if ($user->save())
            {
                $mail         = new MyEmail();
                $mail->type   = MyEmail::TYPE_MERCHANT_PASSWORD_RESET;
                $mail->to     = $user->email;
                $mail->params = array(
                    MyEmail::CODE_USER_NAME => $user->name,
                    MyEmail::CODE_PASSWORD  => $user->new_pass,
                );

                $mail->send();

                $confirm->delete();
                Yii::app()->user->setFlash('success', "New password has been sent to your email.");
                $this->redirect('login');
            }
        }
    }

}

/**
 * End of SiteController
 */